<template>
  <div class="detection-plan-page">
    <el-card class="card-block breadcrumb-card">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>质量管理</el-breadcrumb-item>
        <el-breadcrumb-item>检测管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增检测方案</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <el-card class="card-block form-card">
      <div class="page-header">
        <div>
          <h2>新增检测方案</h2>
          <p class="page-desc">录入检测方案基础信息、检测项目以及关联的物料/产品</p>
        </div>
        <div class="header-actions">
          <el-button @click="handleBack">返回</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存方案</el-button>
        </div>
      </div>

      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="120px" class="plan-form">
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检测方案编号" prop="planCode">
              <el-input v-model="formModel.planCode" :disabled="formModel.useSystemCode" placeholder="请输入方案编号">
                <template #suffix>
                  <span class="system-flag">
                    <span>系统编号</span>
                    <el-switch
                      v-model="formModel.useSystemCode"
                      size="small"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"
                      @change="handlePlanCodeModeChange"
                    />
                  </span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测方案名称" prop="planName">
              <el-input v-model="formModel.planName" placeholder="请输入方案名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检测分类" prop="detectionCategory">
              <el-select v-model="formModel.detectionCategory" placeholder="请选择检测分类" @change="handleDetectionCategoryChange">
                <el-option
                  v-for="item in detectionCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测种类" prop="inspectionType">
              <el-select v-model="formModel.inspectionType" placeholder="请选择检测种类">
                <el-option v-for="item in inspectionTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formModel.status">
                <el-radio-button label="启用" />
                <el-radio-button label="禁用" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formModel.remark" placeholder="请输入备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">缺陷设置</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="是否设置">
              <el-radio-group v-model="formModel.enableDefectSetting">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最低检测数">
              <el-input-number
                v-model="formModel.minInspectionCount"
                :min="0"
                :disabled="!formModel.enableDefectSetting"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="defect-options">
          <el-checkbox v-model="formModel.maxUnqualifiedEnabled" :disabled="!formModel.enableDefectSetting">
            <span>最大不合格数</span>
            <el-input-number
              v-model="formModel.maxUnqualifiedCount"
              :min="0"
              :disabled="!formModel.enableDefectSetting || !formModel.maxUnqualifiedEnabled"
              placeholder="请输入数量"
            />
            <span class="desc">缺陷数量最大大于等于该值时整批判定为不合格</span>
          </el-checkbox>
          <el-checkbox v-model="formModel.criticalDefectEnabled" :disabled="!formModel.enableDefectSetting">
            <span>致命缺陷率(%)</span>
            <el-input-number
              v-model="formModel.criticalDefectRate"
              :min="0"
              :precision="2"
              :disabled="!formModel.enableDefectSetting || !formModel.criticalDefectEnabled"
            />
          </el-checkbox>
          <el-checkbox v-model="formModel.majorDefectEnabled" :disabled="!formModel.enableDefectSetting">
            <span>严重缺陷率(%)</span>
            <el-input-number
              v-model="formModel.majorDefectRate"
              :min="0"
              :precision="2"
              :disabled="!formModel.enableDefectSetting || !formModel.majorDefectEnabled"
            />
          </el-checkbox>
          <el-checkbox v-model="formModel.minorDefectEnabled" :disabled="!formModel.enableDefectSetting">
            <span>轻微缺陷率(%)</span>
            <el-input-number
              v-model="formModel.minorDefectRate"
              :min="0"
              :precision="2"
              :disabled="!formModel.enableDefectSetting || !formModel.minorDefectEnabled"
            />
          </el-checkbox>
        </div>

        <el-divider content-position="left">检测项目</el-divider>
        <div class="table-toolbar">
          <div>
            <el-button type="primary" @click="openTestItemDialog">选择检测项目</el-button>
            <el-button @click="handleManualAddItem">手动添加</el-button>
            <el-button type="danger" plain :disabled="!selectedPlanItemIds.length" @click="handleBatchRemoveItems">
              移除所选
            </el-button>
          </div>
          <span class="table-count">共 {{ planItems.length }} 条</span>
        </div>
        <el-table
          :data="planItems"
          border
          stripe
          style="width: 100%"
          @selection-change="handlePlanItemSelection"
          empty-text="请先通过上方按钮添加检测项目"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column type="index" width="60" label="序号" />
          <el-table-column label="检测项目名称" min-width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.testitemname"
                :disabled="!scope.row.isCustom"
                placeholder="请选择或填写检测项目名称"
              />
            </template>
          </el-table-column>
          <el-table-column label="检测项目编号" min-width="140">
            <template #default="scope">
              <el-input
                v-model="scope.row.testitemcard"
                :disabled="!scope.row.isCustom"
                placeholder="请选择或填写检测项目编号"
              />
            </template>
          </el-table-column>
          <el-table-column label="检测类型" min-width="120">
            <template #default="scope">
              <el-input v-model="scope.row.detectiontypename" disabled />
            </template>
          </el-table-column>
          <el-table-column label="检测工具" min-width="120">
            <template #default="scope">
              <el-input v-model="scope.row.detectiontoolname" disabled />
            </template>
          </el-table-column>
          <el-table-column label="检测要求" min-width="180">
            <template #default="scope">
              <el-input v-model="scope.row.detectionrequirement" placeholder="请输入检测要求" />
            </template>
          </el-table-column>
          <el-table-column label="标准值" min-width="120">
            <template #default="scope">
              <el-input v-model="scope.row.standardvalue" placeholder="请输入标准值" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="110">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="误差上限" width="130">
            <template #default="scope">
              <el-input-number v-model="scope.row.toleranceupper" :precision="3" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="误差下限" width="130">
            <template #default="scope">
              <el-input-number v-model="scope.row.tolerancelower" :precision="3" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" link @click="handleRemovePlanItem(scope.row.uid)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <template v-if="showMaterialSection">
          <el-divider content-position="left">关联物料</el-divider>
          <div class="table-toolbar">
            <div>
              <el-button type="primary" @click="openMaterialDialog">添加</el-button>
              <el-button type="danger" plain :disabled="!selectedMaterialIds.length" @click="handleBatchRemoveMaterials">
                移除所选
              </el-button>
            </div>
            <span class="table-count">共 {{ relatedMaterials.length }} 条</span>
          </div>
          <el-table
            :data="relatedMaterials"
            border
            stripe
            style="width: 100%"
            @selection-change="handleMaterialSelection"
            empty-text="请选择需要关联的物料"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="materialcode" label="物料编号" min-width="140" />
            <el-table-column prop="materialname" label="物料名称" min-width="140" />
            <el-table-column prop="specification" label="规格型号" min-width="140" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="scope">
                <el-button type="danger" size="small" link @click="handleRemoveMaterial(scope.row.materialid)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <template v-else>
          <el-divider content-position="left">关联产品</el-divider>
          <div class="table-toolbar">
            <div>
              <el-button type="primary" @click="openProductDialog">添加</el-button>
              <el-button type="danger" plain :disabled="!selectedProductIds.length" @click="handleBatchRemoveProducts">
                移除所选
              </el-button>
            </div>
            <span class="table-count">共 {{ relatedProducts.length }} 条</span>
          </div>
          <el-table
            :data="relatedProducts"
            border
            stripe
            style="width: 100%"
            @selection-change="handleProductSelection"
            empty-text="请选择需要关联的产品"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="productcard" label="产品编号" min-width="140" />
            <el-table-column prop="productname" label="产品名称" min-width="140" />
            <el-table-column prop="productmodelsame" label="规格型号" min-width="140" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="scope">
                <el-button type="danger" size="small" link @click="handleRemoveProduct(scope.row.productid)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form>
    </el-card>

    <!-- 选择检测项目 -->
    <el-dialog v-model="testItemDialogVisible" title="选择检测项目" width="80%" @open="fetchTestItems">
      <el-form :inline="true" :model="testItemQueryForm" label-width="auto" class="dialog-filter">
        <el-form-item label="检测项目编号/名称">
          <el-input v-model="testItemQueryForm.keyword" placeholder="请输入检测项目编号或名称" clearable />
        </el-form-item>
        <el-form-item label="检测类型">
          <el-select v-model="testItemQueryForm.detectiontypeid" placeholder="请选择检测类型" clearable>
            <el-option
              v-for="item in detectionTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleTestItemQuery">查询</el-button>
          <el-button @click="resetTestItemQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="testItemTableData"
        border
        stripe
        height="420px"
        v-loading="testItemLoading"
        @selection-change="handleTestItemSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="testitemcard" label="检测项目编号" min-width="140" />
        <el-table-column prop="testitemname" label="检测项目名称" min-width="160" />
        <el-table-column prop="detectiontypename" label="检测类型" min-width="120" />
        <el-table-column prop="detectiontoolname" label="检测工具" min-width="120" />
      </el-table>
      <el-pagination
        v-model:current-page="testItemPagination.pageIndex"
        v-model:page-size="testItemPagination.pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="testItemPagination.totalCount"
        :page-sizes="[10, 20, 30, 50]"
        @size-change="handleTestItemSizeChange"
        @current-change="handleTestItemCurrentChange"
        style="margin-top: 12px"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="testItemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmTestItems">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择物料 -->
    <el-dialog v-model="materialDialogVisible" title="选择物料" width="80%" @open="fetchMaterials">
      <el-form :inline="true" :model="materialQueryForm" label-width="auto" class="dialog-filter">
        <el-form-item label="物料编号/名称">
          <el-input v-model="materialQueryForm.keyword" placeholder="请输入物料编号或名称" clearable />
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="materialQueryForm.unit" placeholder="请选择单位" clearable style="width: 150px">
            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料类型">
          <el-select v-model="materialQueryForm.materialtypeid" placeholder="请选择物料类型" clearable style="width: 150px">
            <el-option v-for="item in materialTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料分类">
          <el-select
            v-model="materialQueryForm.materialclassificationid"
            placeholder="请选择物料分类"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in materialCategoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleMaterialQuery">查询</el-button>
          <el-button @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="materialTableData"
        border
        stripe
        height="420px"
        v-loading="materialLoading"
        @selection-change="handleMaterialDialogSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="materialCode" label="物料编号" min-width="140" />
        <el-table-column prop="materialName" label="物料名称" min-width="140" />
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
      </el-table>
      <el-pagination
        v-model:current-page="materialPagination.pageIndex"
        v-model:page-size="materialPagination.pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="materialPagination.totalCount"
        :page-sizes="[10, 20, 30, 50]"
        @size-change="handleMaterialSizeChange"
        @current-change="handleMaterialCurrentChange"
        style="margin-top: 12px"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmMaterials">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择产品 -->
    <el-dialog v-model="productDialogVisible" title="选择产品" width="80%" @open="fetchProducts">
      <el-form :inline="true" :model="productQueryForm" label-width="auto" class="dialog-filter">
        <el-form-item label="产品编号/名称">
          <el-input v-model="productQueryForm.keyword" placeholder="请输入产品编号或名称" clearable />
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="productQueryForm.unit" placeholder="请选择单位" clearable style="width: 150px">
            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型">
          <el-select v-model="productQueryForm.producttypeid" placeholder="请选择产品类型" clearable style="width: 180px">
            <el-option
              v-for="item in productTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品属性">
          <el-select
            v-model="productQueryForm.productattributeid"
            placeholder="请选择产品属性"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in productAttributeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleProductQuery">查询</el-button>
          <el-button @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="productTableData"
        border
        stripe
        height="420px"
        v-loading="productLoading"
        @selection-change="handleProductDialogSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productcard" label="产品编号" min-width="140" />
        <el-table-column prop="productname" label="产品名称" min-width="140" />
        <el-table-column prop="productmodelsame" label="规格型号" min-width="140" />
        <el-table-column prop="productunit" label="单位" width="80" />
      </el-table>
      <el-pagination
        v-model:current-page="productPagination.pageIndex"
        v-model:page-size="productPagination.pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="productPagination.totalCount"
        :page-sizes="[10, 20, 30, 50]"
        @size-change="handleProductSizeChange"
        @current-change="handleProductCurrentChange"
        style="margin-top: 12px"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmProducts">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import https from "@/Http/http";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

interface ApiResultResponse<T> {
  code: number;
  msg: string;
  data: T;
}

interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
}

interface DetectionTypeDTO {
  id: number;
  detectiontypename: string;
}

interface TestItemDTO {
  id: number;
  testitemcard: string;
  testitemname: string;
  detectiontypeid: number;
  detectiontypename: string;
  detectiontoolid: number;
  detectiontoolname: string;
}

interface PlanItemRow {
  uid: string;
  isCustom: boolean;
  testitemid?: number;
  testitemcard: string;
  testitemname: string;
  detectiontypeid?: number;
  detectiontypename?: string;
  detectiontoolid?: number;
  detectiontoolname?: string;
  detectionrequirement?: string;
  standardvalue?: string;
  unit?: string;
  toleranceupper?: number | null;
  tolerancelower?: number | null;
  remark?: string;
}

interface MaterialRow {
  materialid: number;
  materialcode: string;
  materialname: string;
  specification?: string;
  unit?: string;
  materialtypeid?: number;
  materialclassificationid?: number;
}

interface ProductRow {
  productid: number;
  productcard: string;
  productname: string;
  productmodelsame?: string;
  unit?: string;
  producttypeid?: number;
  productattributeid?: number;
}

const router = useRouter();
const formRef = ref<FormInstance>();
const submitLoading = ref(false);

const formModel = reactive({
  planCode: "",
  planName: "",
  detectionCategory: "物料检测",
  inspectionType: "首检",
  status: "启用",
  remark: "",
  useSystemCode: true,
  enableDefectSetting: true,
  minInspectionCount: 0,
  maxUnqualifiedEnabled: false,
  maxUnqualifiedCount: 0,
  criticalDefectEnabled: false,
  criticalDefectRate: 0,
  majorDefectEnabled: false,
  majorDefectRate: 0,
  minorDefectEnabled: false,
  minorDefectRate: 0,
});

const rules = reactive<FormRules>({
  planCode: [{ required: true, message: "请输入检测方案编号", trigger: "blur" }],
  planName: [{ required: true, message: "请输入检测方案名称", trigger: "blur" }],
  detectionCategory: [{ required: true, message: "请选择检测分类", trigger: "change" }],
  inspectionType: [{ required: true, message: "请选择检测种类", trigger: "change" }],
});

const detectionCategoryOptions = [
  { label: "物料检测", value: "物料检测" },
  { label: "产品检测", value: "产品检测" },
];
const inspectionTypeOptions = ["首检", "自检", "末检", "巡检", "终检"];

const planItems = ref<PlanItemRow[]>([]);
const selectedPlanItemIds = ref<string[]>([]);

const relatedMaterials = ref<MaterialRow[]>([]);
const selectedMaterialIds = ref<number[]>([]);

const relatedProducts = ref<ProductRow[]>([]);
const selectedProductIds = ref<number[]>([]);

const detectionTypesSource = ref<DetectionTypeDTO[]>([]);
const detectionTypeOptions = computed(() =>
  detectionTypesSource.value.map((item) => ({ label: item.detectiontypename, value: item.id })),
);

const showMaterialSection = computed(() => formModel.detectionCategory === "物料检测");

const generatePlanCode = () => {
  const now = new Date();
  return `JHFA${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, "0")}${now
    .getDate()
    .toString()
    .padStart(2, "0")}${now.getHours().toString().padStart(2, "0")}${now
    .getMinutes()
    .toString()
    .padStart(2, "0")}${now.getSeconds().toString().padStart(2, "0")}`;
};

const handlePlanCodeModeChange = () => {
  if (formModel.useSystemCode) {
    formModel.planCode = generatePlanCode();
  } else {
    formModel.planCode = "";
  }
};

const handleDetectionCategoryChange = () => {
  selectedMaterialIds.value = [];
  selectedProductIds.value = [];
  if (showMaterialSection.value) {
    relatedProducts.value = [];
  } else {
    relatedMaterials.value = [];
  }
};

const createUid = () => {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
    return crypto.randomUUID();
  }
  return `plan-${Date.now()}-${Math.random().toString(16).slice(2)}`;
};

const handleManualAddItem = () => {
  planItems.value.push({
    uid: createUid(),
    isCustom: true,
    testitemcard: "",
    testitemname: "",
  });
};

const handlePlanItemSelection = (rows: PlanItemRow[]) => {
  selectedPlanItemIds.value = rows.map((item) => item.uid);
};

const handleRemovePlanItem = (uid: string) => {
  planItems.value = planItems.value.filter((item) => item.uid !== uid);
};

const handleBatchRemoveItems = () => {
  planItems.value = planItems.value.filter((item) => !selectedPlanItemIds.value.includes(item.uid));
  selectedPlanItemIds.value = [];
};

const handleMaterialSelection = (rows: MaterialRow[]) => {
  selectedMaterialIds.value = rows.map((item) => item.materialid);
};

const handleRemoveMaterial = (id: number) => {
  relatedMaterials.value = relatedMaterials.value.filter((item) => item.materialid !== id);
};

const handleBatchRemoveMaterials = () => {
  relatedMaterials.value = relatedMaterials.value.filter((item) => !selectedMaterialIds.value.includes(item.materialid));
  selectedMaterialIds.value = [];
};

const handleProductSelection = (rows: ProductRow[]) => {
  selectedProductIds.value = rows.map((item) => item.productid);
};

const handleRemoveProduct = (id: number) => {
  relatedProducts.value = relatedProducts.value.filter((item) => item.productid !== id);
};

const handleBatchRemoveProducts = () => {
  relatedProducts.value = relatedProducts.value.filter((item) => !selectedProductIds.value.includes(item.productid));
  selectedProductIds.value = [];
};

const validateDefectSettings = () => {
  if (!formModel.enableDefectSetting) {
    return true;
  }
  if (formModel.maxUnqualifiedEnabled && (!formModel.maxUnqualifiedCount || formModel.maxUnqualifiedCount <= 0)) {
    ElMessage.warning("请填写最大不合格数");
    return false;
  }
  if (formModel.criticalDefectEnabled && (!formModel.criticalDefectRate || formModel.criticalDefectRate <= 0)) {
    ElMessage.warning("请填写致命缺陷率");
    return false;
  }
  if (formModel.majorDefectEnabled && (!formModel.majorDefectRate || formModel.majorDefectRate <= 0)) {
    ElMessage.warning("请填写严重缺陷率");
    return false;
  }
  if (formModel.minorDefectEnabled && (!formModel.minorDefectRate || formModel.minorDefectRate <= 0)) {
    ElMessage.warning("请填写轻微缺陷率");
    return false;
  }
  return true;
};

const buildSubmitPayload = () => {
  return {
    plancode: formModel.planCode,
    issystemcode: formModel.useSystemCode,
    planname: formModel.planName,
    detectioncategory: formModel.detectionCategory,
    inspectiontype: formModel.inspectionType,
    planstate: formModel.status,
    plandes: formModel.remark,
    enabledefectsetting: formModel.enableDefectSetting,
    mininspectioncount: formModel.minInspectionCount,
    enablemaxunqualified: formModel.maxUnqualifiedEnabled,
    maxunqualifiedcount: formModel.maxUnqualifiedEnabled ? formModel.maxUnqualifiedCount : null,
    enablecriticaldefectrate: formModel.criticalDefectEnabled,
    criticaldefectrate: formModel.criticalDefectEnabled ? formModel.criticalDefectRate : null,
    enablemajordefectrate: formModel.majorDefectEnabled,
    majordefectrate: formModel.majorDefectEnabled ? formModel.majorDefectRate : null,
    enableminordefectrate: formModel.minorDefectEnabled,
    minordefectrate: formModel.minorDefectEnabled ? formModel.minorDefectRate : null,
    items: planItems.value.map((item, index) => ({
      testitemid: item.testitemid ?? null,
      testitemcard: item.testitemcard,
      testitemname: item.testitemname,
      detectiontypeid: item.detectiontypeid,
      detectiontypename: item.detectiontypename,
      detectiontoolid: item.detectiontoolid,
      detectiontoolname: item.detectiontoolname,
      detectionrequirement: item.detectionrequirement,
      standardvalue: item.standardvalue,
      unit: item.unit,
      toleranceupper: item.toleranceupper,
      tolerancelower: item.tolerancelower,
      remark: item.remark,
      sortorder: index + 1,
    })),
    materials: showMaterialSection.value
      ? relatedMaterials.value.map((item) => ({
          materialid: item.materialid,
          materialcode: item.materialcode,
          materialname: item.materialname,
          specification: item.specification,
          unit: item.unit,
          materialtypeid: item.materialtypeid,
          materialclassificationid: item.materialclassificationid,
        }))
      : [],
    products: showMaterialSection.value
      ? []
      : relatedProducts.value.map((item) => ({
          productid: item.productid,
          productcard: item.productcard,
          productname: item.productname,
          productmodelsame: item.productmodelsame,
          unit: item.unit,
          producttypeid: item.producttypeid,
          productattributeid: item.productattributeid,
        })),
  };
};

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    if (!planItems.value.length) {
      ElMessage.warning("请至少添加一个检测项目");
      return;
    }
    const invalidItem = planItems.value.find((item) => !item.testitemname || !item.testitemcard);
    if (invalidItem) {
      ElMessage.warning("检测项目名称与编号不能为空");
      return;
    }
    if (!validateDefectSettings()) {
      return;
    }
    submitLoading.value = true;
    try {
      const payload = buildSubmitPayload();
      const { data } = await https.Writes.post<ApiResultResponse<number>>("/Detection/DetectionPlanAdd", payload);
      if (data.code !== 1) {
        throw new Error(data.msg || "保存失败");
      }
      ElMessage.success("检测方案新增成功");
      // 设置标记，表示从新增页面返回
      sessionStorage.setItem("fromDetectionPlanAdd", "true");
      router.push("/DetectionPlanList");
    } catch (error: any) {
      console.error(error);
      ElMessage.error(error.message || "保存失败");
    } finally {
      submitLoading.value = false;
    }
  });
};

const handleBack = () => {
  router.back();
};

// 选择检测项目对话框
const testItemDialogVisible = ref(false);
const testItemLoading = ref(false);
const testItemQueryForm = reactive({
  keyword: "",
  detectiontypeid: undefined as number | undefined,
});
const testItemTableData = ref<TestItemDTO[]>([]);
const testItemSelection = ref<TestItemDTO[]>([]);
const testItemPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const openTestItemDialog = () => {
  testItemDialogVisible.value = true;
};

const fetchTestItems = async () => {
  testItemLoading.value = true;
  try {
    const params: Record<string, any> = {
      pageindex: testItemPagination.pageIndex,
      pagesize: testItemPagination.pageSize,
    };
    if (testItemQueryForm.keyword) {
      params.testitemname = testItemQueryForm.keyword;
    }
    if (testItemQueryForm.detectiontypeid) {
      params.detectiontypeid = testItemQueryForm.detectiontypeid;
    }
    const { data } = await https.Reads.get<ApiPageingResponse<TestItemDTO>>("/Detection/TestItemList", {
      params,
    });
    if (data.code === 1) {
      testItemTableData.value = data.data || [];
      testItemPagination.totalCount = data.totalCount || 0;
    } else {
      throw new Error(data.msg || "获取检测项目失败");
    }
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取检测项目失败");
  } finally {
    testItemLoading.value = false;
  }
};

const handleTestItemQuery = () => {
  testItemPagination.pageIndex = 1;
  fetchTestItems();
};

const resetTestItemQuery = () => {
  testItemQueryForm.keyword = "";
  testItemQueryForm.detectiontypeid = undefined;
  handleTestItemQuery();
};

const handleTestItemSelection = (rows: TestItemDTO[]) => {
  testItemSelection.value = rows;
};

const handleTestItemSizeChange = (size: number) => {
  testItemPagination.pageSize = size;
  fetchTestItems();
};

const handleTestItemCurrentChange = (page: number) => {
  testItemPagination.pageIndex = page;
  fetchTestItems();
};

const handleConfirmTestItems = () => {
  if (!testItemSelection.value.length) {
    ElMessage.warning("请选择检测项目");
    return;
  }
  const exists = new Set(planItems.value.map((item) => item.testitemid));
  testItemSelection.value.forEach((item) => {
    if (exists.has(item.id)) return;
    planItems.value.push({
      uid: createUid(),
      isCustom: false,
      testitemid: item.id,
      testitemcard: item.testitemcard,
      testitemname: item.testitemname,
      detectiontypeid: item.detectiontypeid,
      detectiontypename: item.detectiontypename,
      detectiontoolid: item.detectiontoolid,
      detectiontoolname: item.detectiontoolname,
    });
  });
  testItemDialogVisible.value = false;
  testItemSelection.value = [];
};

// 物料选择
const materialDialogVisible = ref(false);
const materialLoading = ref(false);
const materialQueryForm = reactive({
  keyword: "",
  unit: "",
  materialtypeid: undefined as number | undefined,
  materialclassificationid: undefined as number | undefined,
});
const materialTableData = ref<any[]>([]);
const materialDialogSelection = ref<any[]>([]);
const materialPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const unitOptions = [
  { label: "个", value: "个" },
  { label: "件", value: "件" },
  { label: "台", value: "台" },
  { label: "套", value: "套" },
  { label: "kg", value: "kg" },
  { label: "g", value: "g" },
];

const materialTypeOptions = [
  { label: "类型一", value: 1 },
  { label: "类型二", value: 2 },
  { label: "类型三", value: 3 },
];

const materialCategoryOptions = [
  { label: "分类一", value: 1 },
  { label: "分类二", value: 2 },
  { label: "分类三", value: 3 },
];

const openMaterialDialog = () => {
  materialDialogVisible.value = true;
};

const fetchMaterials = async () => {
  materialLoading.value = true;
  try {
    const params: Record<string, any> = {
      pageindex: materialPagination.pageIndex,
      pagesize: materialPagination.pageSize,
    };
    if (materialQueryForm.keyword) {
      params.materialname = materialQueryForm.keyword;
    }
    if (materialQueryForm.materialtypeid) {
      params.materialtypeid = materialQueryForm.materialtypeid;
    }
    if (materialQueryForm.materialclassificationid) {
      params.materialclassificationid = materialQueryForm.materialclassificationid;
    }
    const { data } = await https.Reads.get<ApiPageingResponse<any>>("/Material/MaterialGetList", {
      params,
    });
    if (data.code === 1) {
      let list = data.data || [];
      if (materialQueryForm.unit) {
        list = list.filter(
          (item: any) =>
            (item.materialunit || item.unit || "").toLowerCase() === materialQueryForm.unit.toLowerCase(),
        );
        materialPagination.totalCount = list.length;
      } else {
        materialPagination.totalCount = data.totalCount || 0;
      }
      materialTableData.value = list.map((item: any) => ({
        id: item.id,
        materialCode: item.materialcard,
        materialName: item.materialname,
        specification: item.materialmodelsame,
        unit: item.materialunit,
        materialid: item.id,
        materialcode: item.materialcard,
        materialname: item.materialname,
        materialtypeid: item.materialtypeid,
        materialclassificationid: item.materialclassificationid,
      }));
    } else {
      throw new Error(data.msg || "获取物料失败");
    }
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取物料失败");
  } finally {
    materialLoading.value = false;
  }
};

const handleMaterialQuery = () => {
  materialPagination.pageIndex = 1;
  fetchMaterials();
};

const resetMaterialQuery = () => {
  materialQueryForm.keyword = "";
  materialQueryForm.unit = "";
  materialQueryForm.materialtypeid = undefined;
  materialQueryForm.materialclassificationid = undefined;
  handleMaterialQuery();
};

const handleMaterialDialogSelection = (rows: any[]) => {
  materialDialogSelection.value = rows;
};

const handleMaterialSizeChange = (size: number) => {
  materialPagination.pageSize = size;
  fetchMaterials();
};

const handleMaterialCurrentChange = (page: number) => {
  materialPagination.pageIndex = page;
  fetchMaterials();
};

const handleConfirmMaterials = () => {
  if (!materialDialogSelection.value.length) {
    ElMessage.warning("请选择物料");
    return;
  }
  const exists = new Set(relatedMaterials.value.map((item) => item.materialid));
  materialDialogSelection.value.forEach((item: any) => {
    if (exists.has(item.id)) return;
    relatedMaterials.value.push({
      materialid: item.id,
      materialcode: item.materialCode ?? item.materialcard ?? "",
      materialname: item.materialName ?? item.materialname ?? "",
      specification: item.specification ?? item.materialModelSame ?? "",
      unit: item.unit ?? item.materialUnit ?? "",
      materialtypeid: item.materialtypeid || null,
      materialclassificationid: item.materialclassificationid || null,
    });
  });
  materialDialogVisible.value = false;
  materialDialogSelection.value = [];
};

// 产品选择
const productDialogVisible = ref(false);
const productLoading = ref(false);
const productQueryForm = reactive({
  keyword: "",
  unit: "",
  producttypeid: undefined as number | undefined,
  productattributeid: undefined as number | undefined,
});
const productTableData = ref<any[]>([]);
const productDialogSelection = ref<any[]>([]);
const productPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const productTypeOptions = [
  { label: "类型一", value: 1 },
  { label: "类型二", value: 2 },
  { label: "类型三", value: 3 },
];
const productAttributeOptions = [
  { label: "自制", value: 1 },
  { label: "外购", value: 2 },
];

const openProductDialog = () => {
  productDialogVisible.value = true;
};

const fetchProducts = async () => {
  productLoading.value = true;
  try {
    const params: Record<string, any> = {
      pageindex: productPagination.pageIndex,
      pagesize: productPagination.pageSize,
    };
    if (productQueryForm.keyword) {
      params.productname = productQueryForm.keyword;
    }
    if (productQueryForm.producttypeid) {
      params.producttypeid = productQueryForm.producttypeid;
    }
    if (productQueryForm.productattributeid) {
      params.productattributeid = productQueryForm.productattributeid;
    }
    const { data } = await https.Reads.get<ApiPageingResponse<any>>("/Product/ProductGetList", {
      params,
    });
    if (data.code === 1) {
      let list = data.data || [];
      if (productQueryForm.unit) {
        list = list.filter(
          (item: any) => (item.productunit || item.unit || "").toLowerCase() === productQueryForm.unit.toLowerCase(),
        );
        productPagination.totalCount = list.length;
      } else {
        productPagination.totalCount = data.totalCount || 0;
      }
      productTableData.value = list;
    } else {
      throw new Error(data.msg || "获取产品失败");
    }
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取产品失败");
  } finally {
    productLoading.value = false;
  }
};

const handleProductQuery = () => {
  productPagination.pageIndex = 1;
  fetchProducts();
};

const resetProductQuery = () => {
  productQueryForm.keyword = "";
  productQueryForm.unit = "";
  productQueryForm.producttypeid = undefined;
  productQueryForm.productattributeid = undefined;
  handleProductQuery();
};

const handleProductDialogSelection = (rows: any[]) => {
  productDialogSelection.value = rows;
};

const handleProductSizeChange = (size: number) => {
  productPagination.pageSize = size;
  fetchProducts();
};

const handleProductCurrentChange = (page: number) => {
  productPagination.pageIndex = page;
  fetchProducts();
};

const handleConfirmProducts = () => {
  if (!productDialogSelection.value.length) {
    ElMessage.warning("请选择产品");
    return;
  }
  const exists = new Set(relatedProducts.value.map((item) => item.productid));
  productDialogSelection.value.forEach((item: any) => {
    if (exists.has(item.id)) return;
    relatedProducts.value.push({
      productid: item.id,
      productcard: item.productcard,
      productname: item.productname,
      productmodelsame: item.productmodelsame,
      unit: item.productunit,
      producttypeid: item.producttypeid,
      productattributeid: item.productattributeid,
    });
  });
  productDialogVisible.value = false;
  productDialogSelection.value = [];
};

const fetchDetectionTypes = async () => {
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<DetectionTypeDTO>>("/Detection/DetectionTypeList", {
      params: { pageindex: 1, pagesize: 999 },
    });
    if (data.code === 1) {
      detectionTypesSource.value = data.data || [];
    }
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  handlePlanCodeModeChange();
  fetchDetectionTypes();
});
</script>

<style scoped>
.detection-plan-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: linear-gradient(135deg, #f0f4ff 0%, #fef5f6 45%, #fdf8ff 100%);
}

.card-block {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.6);
}

.form-card {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-desc {
  margin: 0;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.plan-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.system-flag {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 12px;
}

.defect-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}

.defect-options .el-checkbox {
  display: flex;
  align-items: center;
  gap: 12px;
}

.defect-options .desc {
  color: #909399;
  font-size: 12px;
}

.table-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.table-count {
  color: #909399;
}

.dialog-filter {
  margin-bottom: 12px;
}
</style>

